package com.tanhua.dubbo.api.mongo;

import com.tanhua.domain.db.Visitor;
import com.tanhua.domain.mongo.Comment;
import com.tanhua.domain.mongo.Publish;
import com.tanhua.domain.mongo.RecommendUser;
import com.tanhua.domain.vo.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.config.annotation.Service;

import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CommentApiImpl implements CommentApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public int save(Comment comment) {
        //获取动态Id
        ObjectId targetId = comment.getTargetId();
        //根据动态Id查询动态作者的Id
        Publish publishLish = mongoTemplate.findById(targetId, Publish.class);
        comment.setTargetUserId(publishLish.getUserId());
        comment.setCreated(System.currentTimeMillis());
        mongoTemplate.insert(comment);
        //设置更新条件
        Query query = new Query(Criteria.where("_id").is(targetId));
        Update update = new Update();
        update.inc(comment.getCol(), 1);
        mongoTemplate.updateFirst(query, update, Publish.class);
        if (comment.getCommentType() == 2) {
            return 0;
        }
        Publish newPublish = mongoTemplate.findById(targetId, Publish.class);
        switch (comment.getCommentType()) {
            case 1:
                return newPublish.getLikeCount();
            case 3:
                return newPublish.getLoveCount();
            default:
                return 0;
        }
    }

    @Override
    public int remove(Comment comment) {
        //删除评论
        Query query = new Query(Criteria.where("targetId").is(comment.getTargetId()).and("targetType").is(comment.getTargetId()).and("userId").is(comment.getUserId()));
        mongoTemplate.remove(query, Comment.class);
        Query publishQuery = new Query(Criteria.where("_id").is(comment.getTargetId()));
        Update update = new Update();
        //自减
        update.inc(comment.getCol(), -1);
        mongoTemplate.updateFirst(publishQuery, update, Publish.class);
        Publish newPublish = mongoTemplate.findById(comment.getTargetId(), Publish.class);
        switch (comment.getCommentType()) {
            case 1:
                return newPublish.getLikeCount();
            case 3:
                return newPublish.getLoveCount();
            default:
                return 0;
        }
    }

    @Override
    public PageResult findPage(Long page, Long pagesize, String movementId) {
        Query query = new Query(Criteria.where("targetId").is(new ObjectId(movementId)).and("commentType").is(2));
        long total = mongoTemplate.count(query, Comment.class);
        List<Comment> commentList = new ArrayList<>();
        if (total > 0) {
            query.skip((page - 1) * pagesize).limit(pagesize.intValue());
            query.with(Sort.by(Sort.Order.desc("created")));
            commentList = mongoTemplate.find(query, Comment.class);
        }
        return PageResult.pageResult(page, pagesize, commentList, total);
    }

    @Override
    public Integer like(Comment comment) {
        ObjectId targetId = comment.getTargetId();
        Comment byId = mongoTemplate.findById(targetId, Comment.class);
        comment.setTargetUserId(byId.getUserId());
        comment.setCreated(System.currentTimeMillis());
        mongoTemplate.insert(comment);
        Update update = new Update();
        update.inc("likeCount", 1);
        Query query = new Query(Criteria.where("_id").is(targetId));
        mongoTemplate.updateFirst(query, update, Comment.class);
        List<Comment> commentList = mongoTemplate.find(query, Comment.class);
        Integer likeCount = comment.getLikeCount();
        return likeCount;
    }

    @Override
    public List<Visitor> findVisitors(Long longInUserId) {
        Query query = new Query(Criteria.where("userId").is(longInUserId));
        query.with(Sort.by(Sort.Order.desc("date")));
        query.limit(4);
        List<Visitor> visitors = mongoTemplate.find(query, Visitor.class);
        if (!CollectionUtils.isEmpty(visitors)) {
            List<Long> visitorIdList = visitors.stream().map(Visitor::getVisitorUserId).collect(Collectors.toList());
            Query recommentUserQuery = new Query(Criteria.where("toUserId").is(longInUserId).and("userId").is(visitorIdList));
            List<RecommendUser> recommendUsers = mongoTemplate.find(query, RecommendUser.class);
            Map<Long, Double> scoreList = new HashMap<>();
            if (!CollectionUtils.isEmpty(recommendUsers)) {
                scoreList = recommendUsers.stream().collect(Collectors.toMap(RecommendUser::getUserId, RecommendUser::getScore));
            }
            visitors.forEach(visitor -> {
                if (null==visitor.getScore()){
                    visitor.setScore(RandomUtils.nextDouble(60,80));
                }
            });

        }
        return visitors;
    }
}
